
#include "base_protocol.h"
#include "log.h"
namespace secsmart_protocol
{

bool BaseProtocol::setIpPort(secsmart_session::session_sptr session,bool parse_forward,bool data_forward){
    LOG_DEBUG("session_forward={},parse_forward={},data_forward={},sport={},dport={}", 
               (int)session->direction, (int)parse_forward, (int)data_forward,
               session->sport,session->dport);
    if(asset_port == 0){ //未设置资产ip和port，先设置资产ip和port
        if(parse_forward == data_forward){//同方向
            asset_ip = session->dip.toString();
            asset_port = session->dport;
        }else{//反方向
            asset_ip = session->sip.toString();
            asset_port = session->sport;   
        }
        return true;
    }
    //已设置资产ip和port，对资产ip和port进行验证
    bool result = false;
     if(parse_forward == data_forward){//同方向
        if(asset_ip == session->dip.toString() && asset_port == session->dport){
            result = true;
        }
        
     }else{
        if(asset_ip == session->sip.toString() && asset_port == session->sport){
            result = true;
        }
     }
     return result;
}

void BaseProtocol::skipBytesWithLen4(const uint8_t *buf, size_t &position, size_t size)
    {
        uint32_t uiLen = readU32LE(buf,position,size);
        skipLen(position,uiLen);
    }

    void BaseProtocol::readBytesWithLen4(const uint8_t *buf, size_t &position, size_t size,std::string &str)
    {
        uint32_t uiLen = readU32LE(buf,position,size);
        readData(buf,position,size,str,uiLen);
    }

    uint32_t BaseProtocol::readU32LE(const uint8_t *buf,size_t &position,size_t size)
    {
        
            if(position + 3 >= size)
            {
                LOG_ERROR("read data error");
                return 0;
            }
            uint32_t uiLen = (uint32_t)(((buf[position+3] & 0xFF) << 24) | ((buf[position+2] & 0xFF) << 16) | ((buf[position+1] & 0xFF) << 8) | (buf[position] & 0xFF));
            position = position + 4;
            return uiLen;
    }

    void BaseProtocol::skipLen(size_t &position,uint32_t Len)
    {
        position += Len;
    }
    void BaseProtocol::readData(const uint8_t *buf, size_t &position, size_t size,std::string &str, uint32_t wantLen)
    {
        for(size_t  j = 0; position < size && j < wantLen; position++,j++)
        {
            str += buf[position];
        }
    }


};